'use client';
import React, { useRef } from 'react';
import From from '@/components/admin/auth/Form';
import message from '@/components/common/message';
import { LOCAL_USER, ROUTE_DASHBOARD } from '@/config/settings';
import { useRouter } from 'next/navigation';

export default function Login() {
  const formRef = useRef(null);
  const router = useRouter();

  const onFinish = async (e) => {
    e.preventDefault();
    const form = formRef.current;
    const values = { username: form.username.value, password: form.password.value, verificationCode: form.verificationCode.value };
    try {
      const res = await fetch('/api/admin/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(values), });
      const data = await res.json();
      if (data.code === 0 || data.code === 1) {
        message.success(data.codeMap[data.code] || '注册成功');
        await handleLogin(values);
      } else {
        message.error(data.codeMap[data.code] || '注册失败');
      }
    } catch (error) {
      message.error('注册失败');
    }
  };

  const handleLogin = async (values) => {
    try {
      const res = await fetch('/api/admin/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(values),
      });
      const loginData = await res.json();
      if (loginData.code === 0) {
        message.success('登录成功');
        localStorage.setItem(LOCAL_USER, JSON.stringify(loginData.userInfo));
        router.push(ROUTE_DASHBOARD);
      } else {
        message.error(loginData.message || '登录失败');
      }
    } catch {
      message.error('登录失败');
    }
  };

  return (
    <section className="w-full h-screen overflow-hidden grid place-items-center bg-[var(--bg-color)] bg-cover bg-center bg-no-repeat">
      <From formType='register' accountName={'注册账号'} passwordName={'账号密码'} buttonName={'注册'} formRef={formRef} onFinish={onFinish} linkName={'去登录账号'} linkHref={'/admin/auth/login'} />
    </section>
  );
}